/**
 * Created by yongqiang.ren on 16/9/4.
 */
import { mutationWithClientMutationId } from 'graphql-relay';

import {
  cursorForObjectInConnection,
  fromGlobalId,
} from 'graphql-relay';
import {
  GraphQLID,
  GraphQLString,
  GraphQLNonNull,
  GraphQLFloat,
} from 'graphql';

import { User, Company } from '../../models';
import UserType from '../../types/UserType';

import { connectionFromType } from '../../connection';

const AddUserMutation = mutationWithClientMutationId({
  name: 'addUser',
  inputFields: {
    name: { type: new GraphQLNonNull(GraphQLString) },
    email: { type: GraphQLString },
    password: { type: new GraphQLNonNull(GraphQLString) },
    company_id: { type: GraphQLID },
  },
  outputFields: {
    userEdge: {
      type: connectionFromType('user', UserType).edge,
      resolve: async ({ localId, origin }) => {
        const users = await User.findAll({
          org_id: origin.get('company_id'),
        });
        const user = users.find(a => a.get('id') === localId);
        return {
          cursor: cursorForObjectInConnection(users, user),
          node: user,
        };
      },
    },
  },
  mutateAndGetPayload: async ({ name, email, password, company_id }) => {
    console.log(fromGlobalId(company_id))
    const user = await User.create({
      name,
      email,
      password,
      company_id: parseInt(fromGlobalId(company_id).id, 10),
    });
    return { localId: user.dataValues.id, origin: user };
    //return { user };
  },
});

export default AddUserMutation;
